package pt.ipleiria.estg.dei.ei.es2.bio;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;

import pt.ipleiria.estg.dei.ei.es2.bio.modal.Contact;


public class MainActivity extends Activity {

    private static final int REQUEST_CHANGE_CONTACT = 0 ;
    private boolean hasCheckedIn = false;
    private Contact myContacto;
    private SharedPreferences settings;
    private MenuItem itemCheckIn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        settings = PreferenceManager.getDefaultSharedPreferences(this);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        itemCheckIn = menu.findItem(R.id.action_checkin);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_checkin) {
           switchCheckInState();
        }

        return super.onOptionsItemSelected(item);
    }

   private void switchCheckInState(){
       if(!hasCheckedIn){
           if(checkInSharedPreferences()){
               confirmAndCheckIn();
           } else{
               showDataCompletionDialog();
           }
       } else {
           hasCheckedIn = false;
           itemCheckIn.setIcon(R.drawable.ic_action_person);
       }
   }

    private void showDataCompletionDialog() {
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);

        alertBuilder.setTitle(getString(R.string.alertDialogNoDataTittle));
        alertBuilder.setMessage(getString(R.string.alertDialogNoDataMessage)+"\n"+ getString(R.string.alertDialogNoDataQuestion));

        alertBuilder.setPositiveButton(getString(R.string.okBtn), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                completeContactData();
            }
        });

        alertBuilder.setNegativeButton(getString(R.string.cancelBtn),null);

        alertBuilder.show();



    }

    private void completeContactData(){
        startActivityForResult(new Intent(this,SettingsActivity.class), REQUEST_CHANGE_CONTACT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode,resultCode,data);
        if(requestCode == REQUEST_CHANGE_CONTACT && resultCode == SettingsActivity.RESULT_OK){
            if(checkInSharedPreferences()){
            confirmAndCheckIn();}
        }
    }

    private boolean checkInSharedPreferences() {
        String name = settings.getString(getString(R.string.prefs_key_name),"");
        String email = settings.getString(getString(R.string.prefs_key_email),"");

        if(!name.isEmpty() && !email.isEmpty()){
            myContacto = new Contact(name,email);
            return true;
        } else{
            myContacto = null;
            return false;
        }

    }

    private void confirmAndCheckIn() {

                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);

                alertBuilder.setTitle(getString(R.string.confirmationTitle));
                alertBuilder.setMessage(getString(R.string.confirmationMessage)+ "\n" + myContacto);

                alertBuilder.setIcon(android.R.drawable.ic_dialog_alert);


                alertBuilder.setPositiveButton(getString(R.string.okBtn), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        checkIn();
                    }
                });

                alertBuilder.setNegativeButton(getString(R.string.cancelBtn),null);

                alertBuilder.show();
        }

    private void checkIn() {
        if (hasConnectivity()) {
            hasCheckedIn = true;

                itemCheckIn.setIcon(R.drawable.ic_action_group);

                Intent intent = new Intent(getApplicationContext(), ParticipantsListActivity.class);

                intent.putExtra(ParticipantsListActivity.HASCHECKEDIN, hasCheckedIn);

                startActivity(intent);
            } else{
                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
                alertBuilder.setTitle(getString(R.string.alertDialogNoNetworkTittle));
                alertBuilder.setMessage(getString(R.string.alertDialogNoNetworkMessage));
                alertBuilder.show();
        }

        }


    private boolean hasConnectivity() {

        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnectedOrConnecting();

    }


}
